package com.book.servlet;

import com.alibaba.fastjson.JSON;
import com.book.bean.Book;
import com.book.service.BookService;
import com.book.utils.ResultVo;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/book")
public class BookServlet extends BaseServlet{
    private BookService bs = new BookService();
    private ResultVo vo = null;
    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        List<Book> list = bs.selectAll();
        vo = new ResultVo(200,"查询成功",list);
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    public void addBook(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        Map<String, String[]> map = req.getParameterMap();
        Book book = new Book();
        BeanUtils.populate(book,map);
        int i = bs.addBook(book);
        if (i>0){
            vo = new ResultVo(200,"添加成功",i);
        }else{
            vo = new ResultVo(500,"添加失败",i);
        }
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    public void findBookById(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        String bid = req.getParameter("bid");
        Book book = bs.findById(Integer.parseInt(bid));
        vo  = new ResultVo(200,"查询成功",book);
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    public void updateBook(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        Map<String, String[]> map = req.getParameterMap();
        Book book = new Book();
        BeanUtils.populate(book,map);

        int i = bs.updateBook(book);
        if (i>0){
            vo=new ResultVo(200,"修改成功",i);
        }else{
            vo=new ResultVo(500,"修改失败",i);

        }
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }
    public void deleteBook(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        String bid = req.getParameter("bid");
        int i = bs.deleteBook(Integer.parseInt(bid));
        if (i>0){
            vo = new ResultVo(200,"删除成功",i);
        }else {
            vo = new ResultVo(500,"删除失败",i);

        }
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);

    }

}
